package com.juno.cafenoa.cart;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.opengl.Visibility;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.juno.cafenoa.CafeNoa;
import com.juno.cafenoa.Constants;
import com.juno.cafenoa.MainActivity;
import com.juno.cafenoa.R;
import com.juno.cafenoa.TopNavigatorView;
import com.juno.cafenoa.cart.CartTableView.ClickListener;
import com.juno.cafenoa.net.AsyncTaskCompleteListener;
import com.juno.cafenoa.net.HttpPostTask;
import com.juno.cafenoa.util.CafeNoaPreference;
import com.juno.cafenoa.util.Util;
import com.juno.ui.uitableview.model.IListItem;

public class Cart extends Activity {
	Context context;
	private CartTableView cartTableView;
	private TopNavigatorView navi = null;
	private static TextView txtvTotalPrice;

	String orderPayMethod = "";
	String orderContent;
	String orderComment = "";
	String orderPickupTime = "";

	TextView txtvNoCartList;

	// 액티비티가 종료되면 가격이 0원이됨
	@Override
	protected void onPause() {
		txtvTotalPrice.setText("0");
		super.onPause();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Log.d("Cart.java", "onCreate() = ");
		context = this;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_cart);
		navi = (TopNavigatorView) findViewById(R.id.navi_cart);
		navi.init("Cart");

		// 비우기 버튼 정의
		Button btnClearCart = (Button) findViewById(R.id.btnClearCart);
		btnClearCart.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				CafeNoa synchoronizedCart = (CafeNoa) context
						.getApplicationContext();
				synchoronizedCart.clearCartList();
				cartTableView.clearCartList();
				Message msg = Message.obtain(Cart.totalPricehandler,
						Constants.TOTAL_PRICE_RESET);
				totalPricehandler.sendMessage(msg);
				TextView txtvNoCartList = (TextView) findViewById(R.id.txtvNoCartList);
				txtvNoCartList.setVisibility(View.VISIBLE);
			}
		});

		txtvTotalPrice = (TextView) findViewById(R.id.txtvTotalPrice);
		txtvTotalPrice.setText("0");

		Button btnDoOrder = (Button) findViewById(R.id.btnDoOrder);
		btnDoOrder.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!txtvTotalPrice.getText().equals("0")) {
					final PickupTimeAlertView alertView = new PickupTimeAlertView(
							context);
					AlertDialog.Builder ab = new AlertDialog.Builder(context);
					ab.setTitle("픽업 예상 시간");
					ab.setView(alertView);

					ab.setPositiveButton("확인",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Spinner spnPaymentMethod = (Spinner) alertView
											.findViewById(R.id.spnPaymentMethod);
									Log.d("Cart.java",
											"spnPaymentMethod.getSelectedItem()"
													+ spnPaymentMethod
															.getSelectedItem());

									if (spnPaymentMethod.getSelectedItem()
											.equals("현금")) {
										Toast.makeText(context, "현금결제 시작",
												Toast.LENGTH_SHORT).show();
										orderPayMethod = "V";
									} else if (spnPaymentMethod
											.getSelectedItem().equals("카드")) {
										Toast.makeText(context, "카드결제 시작",
												Toast.LENGTH_SHORT).show();
										orderPayMethod = "C";
									} else if (spnPaymentMethod
											.getSelectedItem().equals("포인트")) {
										Toast.makeText(context, "포인트결제 시작",
												Toast.LENGTH_SHORT).show();
										orderPayMethod = "P";
									}

									EditText edtAddtionalOption = (EditText) alertView
											.findViewById(R.id.edtAddtionalOption);
									orderComment = edtAddtionalOption.getText()
											+ "";

									TimePicker timePicker = (TimePicker) alertView
											.findViewById(R.id.timePicker);
									Date date = new Date();
									orderPickupTime = (date.getMonth() + 1)
											+ "월 " + date.getDate() + "일 ";
									orderPickupTime += timePicker
											.getCurrentHour()
											+ ":"
											+ timePicker.getCurrentMinute();
									orderListener.excuteHttpTask();
								}
							});
					ab.setNegativeButton("취소", null);
					AlertDialog alert = ab.create();
					alert.show();
				}
			}
		});

		txtvNoCartList = (TextView) findViewById(R.id.txtvNoCartList);
	}

	@Override
	protected void onResume() {
		// Log.d("Cart.java", "onResume() = ");

		// cartTableView를 찾고 변동된 사항이 있음을 유의해 clear후 새로 view를 그림
		cartTableView = (CartTableView) findViewById(R.id.cartTableView);
		cartTableView.clearCartList();

		// Menu에서 선택된 항목들을 가져옴
		CafeNoa addCartFromMenu = (CafeNoa) context.getApplicationContext();
		ArrayList<CartBasicItem> cartList = addCartFromMenu.getCartList();
		if (cartList.size() == 0) {
			txtvNoCartList.setVisibility(View.VISIBLE);
		} else {
			txtvNoCartList.setVisibility(View.GONE);
			for (int i = 0; i < cartList.size(); i++) {
				// Log.d("Cart.java", "cartList.size() = " + cartList.size());
				cartTableView.addProductInCart(cartList.get(i));
			}
		}
		// 해당 줄을 클릭했을때 Expand
		cartTableView.setClickListener(new ClickListener() {
			@Override
			public void onClick(int index) {
				View view = cartTableView.getViewListContainer().getChildAt(
						index);
				RelativeLayout cartDetailLayout = (RelativeLayout) view
						.findViewById(R.id.cartDetailLayout);
				if (cartDetailLayout.getVisibility() == View.GONE) {
					cartDetailLayout.setVisibility(View.VISIBLE);
				} else {
					cartDetailLayout.setVisibility(View.GONE);
				}
			}
		});
		cartTableView.commit();
		super.onResume();
	}

	public static Handler totalPricehandler = new Handler() {
		public void handleMessage(Message msg) {
			int currentTotalPrice = Integer.valueOf(txtvTotalPrice.getText()
					.toString());
			switch (msg.what) {

			case Constants.TOTAL_PRICE_ADDITION:
				currentTotalPrice += (Integer) msg.obj;
				txtvTotalPrice.setText(currentTotalPrice + "");
				break;
			case Constants.TOTAL_PRICE_SUBTRACTION:
				currentTotalPrice -= (Integer) msg.obj;
				txtvTotalPrice.setText(currentTotalPrice + "");
				break;
			case Constants.TOTAL_PRICE_RESET:
				txtvTotalPrice.setText("0");
			}

		}

	};

	AsyncTaskCompleteListener orderListener = new AsyncTaskCompleteListener() {

		@Override
		public void excuteHttpTask() {
			// Url 세팅.
			String url = Util.getUrl("CoffeOrder");

			ArrayList<NameValuePair> value = new ArrayList<NameValuePair>();
			value.add(new BasicNameValuePair("USER_ID", CafeNoaPreference
					.getUserID(context)));
			value.add(new BasicNameValuePair("USER_PHONE", Util
					.getPhoneNum(context)));

			List<IListItem> list = cartTableView.getCartList();
			LinearLayout cartBasicItemLayout = cartTableView
					.getViewListContainer();
			orderContent = new String();
			for (int i = 0; i < list.size(); i++) {
				
				View cartBasicItemView = cartBasicItemLayout.getChildAt(i);
				orderContent += ((TextView) cartBasicItemView
						.findViewById(R.id.txtvOrderedProductName)).getText();
				orderContent += "/";
				orderContent += ((TextView) cartBasicItemView
						.findViewById(R.id.txtvContractCoffeeAmount)).getText();

				LinearLayout llOption = (LinearLayout) cartBasicItemView
						.findViewById(R.id.llOption);

				for (int j = 0; j < llOption.getChildCount(); j++) {
					OptionBasicItem optionBasicItem = (OptionBasicItem) llOption
							.getChildAt(j);
					if (optionBasicItem.getOptionAmount() != 0) {
						orderContent += "/";
						orderContent += optionBasicItem.getOptionName();
						orderContent += "+";
						orderContent += optionBasicItem.getOptionAmount();
					}
				}

				orderContent += " ";
			}

			value.add(new BasicNameValuePair("ORDER_CONTENT", orderContent));

			if (orderComment == null)
				orderComment = "추가사항 없음";
			value.add(new BasicNameValuePair("ORDER_COMMENT", orderComment));
			Log.d("KYT", orderPickupTime);
			value.add(new BasicNameValuePair("ORDER_PICKUP_TIME",
					orderPickupTime));
			value.add(new BasicNameValuePair("ORDER_PAYMENT_METHOD",
					orderPayMethod));
			value.add(new BasicNameValuePair("ORDER_PRICE", txtvTotalPrice
					.getText() + ""));
			HttpPostTask http = new HttpPostTask(context, value, url,
					orderListener);
			http.execute();
		}

		@Override
		public void onTaskComplete(String result, boolean taskOk) {
			Log.v("result", "reuslt :" + result);

			// http 통신 실행후 서버로부터 오는 내용.
			if (taskOk) {
				int code = -1;

				try {
					JSONObject object = new JSONObject(result);
					code = object.getInt("RESULT");
				} catch (JSONException e) {
					e.printStackTrace();
				}

				if (code == -1) {
					Log.v("CafeNoa", "Server Error No code!");
					return;
				}

				if (code == Constants.NETWORK_SUCCESS) {
					// 서버와 통신 성공시 프리퍼런스로 아이디를 저장함.
					Toast.makeText(context, "주문 성공하였습니다", Toast.LENGTH_SHORT)
							.show();
					Log.v("CafeNoa", "Order Success");

					CafeNoa synchoronizedCart = (CafeNoa) context
							.getApplicationContext();
					synchoronizedCart.clearCartList();
					cartTableView.clearCartList();
					Message msg = Message.obtain(Cart.totalPricehandler,
							Constants.TOTAL_PRICE_RESET);
					totalPricehandler.sendMessage(msg);
					txtvNoCartList.setVisibility(View.VISIBLE);
				} else {
					// Order 실패시 처리
				}
			}
		}

	};
}
